/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 98152
 * Date: 2024-10-17
 * Time: 21:19
 */
class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param board string字符串一维数组
     * @param word string字符串
     * @return bool布尔型
     */
    public boolean exist (String[] board, String word) {
        // write code here
        int i = 0;
        for (int row = 0; row < board.length; row++) {
            int m = row;
            for (int col = 0; col < board[row].length(); col++) {
                int n = col;
                i = 0;
                //System.out.println(board[m].charAt(n));
                //System.out.println(word.charAt(i));
                boolean flagUp = true;
                boolean flagDown = true;
                boolean flagLeft = true;
                boolean flagRight = true;
                while (board[m].charAt(n) == word.charAt(i) && ++i < word.length()) {
                    //上
                    if (flagUp && m - 1 >= 0 && board[m - 1].charAt(n) == word.charAt(i)) {
                        m = m - 1;
                        flagUp = true;
                        flagDown = false;
                        flagLeft = true;
                        flagRight = true;
                        continue;
                    }
                    //下
                    if (flagDown && m + 1 < board.length && board[m + 1].charAt(n) == word.charAt(i)) {
                        flagUp = false;
                        flagDown = true;
                        flagLeft = true;
                        flagRight = true;
                        m = m + 1;
                        continue;
                    }
                    //左
                    if(flagLeft && n -1 >= 0 && board[m].charAt(n-1) == word.charAt(i)) {
                        flagUp = true;
                        flagDown = true;
                        flagLeft = true;
                        flagRight = false;
                        n = n - 1;
                        continue;
                    }
                    //右
                    if(flagRight && n + 1 < board[m].length() && board[m].charAt(n + 1) == word.charAt(i)) {
                        flagUp = true;
                        flagDown = true;
                        flagLeft = false;
                        flagRight = true;
                        n = n + 1;
                        continue;
                    }
                }
                if(i == word.length()) {
                    return true;
                }
            }
        }
        return false;
    }
}
public class Test2 {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] board = {"XYZE","SFZS","XDEE"};
        String word = "XYZY";
        System.out.println(solution.exist(board, word));
    }
}
